package org.example.aiagent.demo.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.aiagent.demo.constant.FileConstant;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.net.URLConnection;


@RestController
public class FileDownloadController {
    // 使用 FileConstant 中的文件保存目录路径
    private static final String FILE_STORAGE_PATH = FileConstant.FILE_SAVE_DIR;

    @GetMapping("/download/{filename}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable("filename") String filename, HttpServletResponse response) {
        // 构建文件的完整路径
        File file = new File(FILE_STORAGE_PATH + "/" + filename);
        // 检查文件是否存在
        if (!file.exists()) {
            throw new RuntimeException("文件未找到");
        }

        // 获取文件的 MIME 类型
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = "application/octet-stream";  // 默认类型
        }

        // 设置响应头，通知浏览器下载文件
        response.setContentType(mimeType);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));

        // 使用 FileSystemResource 作为响应体来返回文件内容
        FileSystemResource resource = new FileSystemResource(file);

        return ResponseEntity.ok().body(resource);
    }
}
